package com.bruce.starts.demo.commonerror.cachedesign;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author luotuan
 * @Description
 * @create 2021-05-13 16:37
 **/
@RestController
@Slf4j
@RequestMapping("cacheinvalid")
public class CacheInvalidController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private AtomicInteger atomicInteger = new AtomicInteger();

    @PostConstruct
    public void initWrong() {
        IntStream.rangeClosed(1, 1000).forEach(i -> stringRedisTemplate.opsForValue().set("city" + i, getCityFromDb(i),
                30+ThreadLocalRandom.current().nextInt(10), TimeUnit.SECONDS));
        log.info("cache init finished");
        //Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> log.info("DB QPS: {}", atomicInteger.getAndSet(0)), 0, 1, TimeUnit.SECONDS);
    }

    @GetMapping("city")
    public String city() {
        int id = ThreadLocalRandom.current().nextInt(1000) + 1;
        String key = "city" + id;
        String data = stringRedisTemplate.opsForValue().get(key);
        if (data == null) {
            data = getCityFromDb(id);
            if (StringUtils.isNotBlank(data)) {
                stringRedisTemplate.opsForValue().set(key, data, 30+ThreadLocalRandom.current().nextInt(10), TimeUnit.SECONDS);
            }
        }
        return data;
    }

    private String getCityFromDb(int cityId) {
        atomicInteger.incrementAndGet();
        return "citydata" + System.currentTimeMillis();
    }
}
